import http from '../../../../utils/http.js';
var common = require("../../../public")
Page({
    /**
     * 页面的初始数据
     */
    data: {
        userInfoList:[],
        show: false,//底部弹框
        bottomcheck: false,//弹出框单选框初始值,
        payShow: true,//支付
        who: 0,//确定吊起哪个弹框
        boxChecked: false,//复选框
        userInfo: [],//已经添加购票人列表
        result: "",//点击新增购票人的复选框
        selectedPeople: [],//已经选择的购票人
        userDate: {},//用户信息
        pay: [1, 2, 3],//1余额2支付包3微信
        radio: '1',
        payWay: 1,//支付方式
        // couponResult:['a', 'b'],//优惠券result
        couponArray: [],//点击优惠券的复选框
        coupon: [],//优惠券列表
        arr: [1, 2, 3],
        timePrice: 11,
        cityCouponNo:"",
        flags: true, //控制开关
        totalPrice:0, //总金额
        chooseTime: {}//选择的时间以及场地
    },
        // 券确定
    ComPany_submit() {
            this.setData({
                showCouponsPanel: false,
            })
            // console.log(this.data.comL, "dkdddiokdjd")
        },
    click_company(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        // ticketPrice*ticketNum < item.discountsMoney
        if (that.data.timePrice < item.exceedMoney && that.data.flags && that.data.couponList.length != 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (that.data.flags && that.data.timePrice < item.exceedMoney && that.data.couponList.length == 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (!that.data.flags && item.isSelect != true) {
            common.showToast('此为单选，请先取消选中')
            return
        }
        for (var i = 0; i < this.data.couponList.length; i++) {
            if (i == index) {
                this.data.couponList[i].isSelect = !this.data.couponList[i].isSelect
            } else {
                this.data.couponList[i].isSelect = false
            }
        }
        if (!item.isSelect) {
            var totalPrice = item.discountsMoney //单选的优惠金额
            var ToTAL = ((this.data.timePrice * 100) - (item.discountsMoney * 100)) / 100
        } else {
            var totalPrice = 0
            var ToTAL = ((this.data.timePrice * 100) + (item.discountsMoney * 100)) / 100
        }
        this.setData({
            discountsMoney: totalPrice,
            couponList: this.data.couponList,
            totalPrice: ToTAL,
        }, () => {
            console.log(this.data.totalPrice,"99999")

            var inde = this.data.couponList.findIndex(t => t.isSelect == true)
            var coupObj = inde != -1 ? this.data.couponList[inde] : ''
            that.setData({
                cityCouponNo: coupObj.couponNo
            })
            if (this.data.couponList.findIndex(targrt => targrt.isSelect == true) == -1) {
                that.setData({
                    flags: true
                })

            } else {
                that.setData({
                    flags: false
                })
            }
        })

    },

    getCoupon() { // 获取景区门票可用优惠券
        const that = this
        const tempJson = {
            userId: that.data.userDate.id,
            token: that.data.token,
            venueId: that.data.chooseTime.venueId,
            ticketId: '',
            buyNums: 1
        }
        common.post("/order/getUserCityDiscountCouponForScenicTicket", tempJson, function (res) {
            for (let i = 0; i < res.data.length; i++) {
                res.data[i].isSelect = false
            }
            if (res.status === 200) {
                that.setData({
                    couponList: res.data
                })
            }
        })
    },
    //优惠券
    openCouponsPanel() {
        this.setData({
            showCouponsPanel: true
        })
    },
    closeCouponsPanel() {
        this.setData({
            showCouponsPanel: false
        })
    },
    // 场馆优惠券
    getCoupon() {
        const that = this
        const tempJson = {
            userId: that.data.userDate.id,
            // token: that.data.token,
            venueTimeId:that.data.chooseTime.venueTimeId,
            storeId: this.data.chooseTime.storeId
        }
        common.post("/venueOrder/getUserCityDiscountCouponByStore", tempJson, function (res) {
            for (let i = 0; i < res.data.length; i++) {
                res.data[i].isSelect = false
            }
            if (res.status === 200) {
                that.setData({
                    couponList: res.data
                })
            }
        })
    },
    //获取选择时间页面传来的值
    onLoad(option) {
        console.log(option, '5444552256565555')
        const that = this
       
        let chooseTime = option
        this.setData({
            chooseTime,
            totalPrice:option.money ? option.money : 130,
            timePrice:option.timePrice ? option.timePrice : 130
        }, () => {
          
            that.getCoupon()
        })

    },
    onShow() {
     
        const that = this
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userDate: data.user,
                    token: data.token,
                    openid: data.openid,
                }, function () {
                    this.getpuyTicketList()//购票人列表
                    // this.getCoupon() //优惠券
                })
            } else {
                that.setData({
                    userDate: null,
                    token: '',
                })
            }
        }, true)

    },
    //获取购票人列表
    async getpuyTicketList() {
        let userDetail = wx.getStorageSync('user')
        let option = {
            url: "/scenicTicket/ticketBuyer/getScenicTicketBuyerList",
            data: {
                userId: userDetail.user.id,
                token: userDetail.token
            },
        }
        let res = await http(option)
     
        // if (res.status == 200) {
            this.setData({
                userInfoList: res.data.data
            },()=>{
                console.log(this.data.userInfoList)
            })
        // }
    },
    //点击优惠券的复选框
    couponResult(event) {
        var that = this
        var array = event.detail
        this.setData({
            couponArray: array,
        });
        console.log(event);
    },
    //获取支付的方式 1余额2支付包3微信
    payWay(event) {
        this.setData({
            radio: event.detail,
        });
    },
    payOne(event) {
        // this.toPaymeny()
        this.determine()
      
    },
    //跳转到支付成功页面
    toPaymeny(res) {
        // console.log(Number(this.data.payWay));
        let that = this
        // if(Number(this.data.payWay) == 3){
        var tempJson = {
            orderId: res,
            token: this.data.token,
            openid: this.data.openid,
            userId: this.data.userDate.id
        };
        common.wxPayRequest("/chinaumsPayForVenue", tempJson, function (res) {
            console.log(res);
            if (res.status == 200) {
                wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonceStr,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    'success': function (res) {
                        console.log(res);
                        common.showToast('支付成功', 'success')
                        that.setData({
                            showPop: false,
                            backToApp: true
                        }, _ => {
                            // that.getDrawInfo()
                            wx.navigateTo({
                                url: '../payment/payment?orderNo=' + that.orderNo + '&money=' + that.data.totalPrice
                            })
                        })
                    },
                    'fail': function (res) {
                        if (res.errMsg === 'requestPayment:fail cancel') {
                        } else {
                            common.showToast(res.errMsg)
                        }
                        wx.navigateTo({
                            url: '/packageA/pages/Goods/book/index',
                        })
                        //   if (that.data.fromSmallProgramm == true) { // 从小程序支付页面跳转
                        //     // console.log('小程序跳转到的')
                        //     that.setData({
                        //       paySuccess: false,
                        //     })
                        //     // that.popPage()
                        //   } else {
                        //     // console.log('app跳转到的')
                        //     that.setData({
                        //       payStatus: true,
                        //       paySuccess: false,
                        //     })
                        //   }
                    }
                })
            }else{
                common.showToast(res.msg)
            }
        })
        // }else{
        //     wx.showToast({
        //       title: '请选择支付方式',
        //     })
        // }
        // wx.navigateTo({
        //     url: '../payment/payment?orderNo='+this.orderNo
        // })
    },
    //点击新增购票人的复选框
    payPeople(event) {
        var that = this
        var array = event.detail
        console.log(event,"000000")
        that.setData({
            result: array
        })
    },
    //确定购票人
    addPeople() {
        if (this.data.result == []) {
            wx.showToast({
                title: '您还没有添加用户',
                icon: "none"
            })
            return
        } else {
            let user = this.data.userInfoList//可以购票人列表
            let event = this.data.result //点击的购票人
            let only = this.data.selectedPeople.findIndex((item, index) => {
                return item.id == event
            })
          
            if (only == -1 && this.data.selectedPeople.length == 0) {
                let ind = user.findIndex((item) => {
                    return item.id == event
                })
                let changePeople = this.data.userInfoList[ind]
                this.data.selectedPeople.push(changePeople)
                this.setData({
                    selectedPeople: this.data.selectedPeople,
                    show: false
                })
            } else if (this.data.selectedPeople.length != 0) {
                wx.showToast({
                    title: '只需选择一个人',
                    icon: "none"
                })
                this.setData({
                    show: false
                })
                return
            }
            // for (var m = 0; m < len; m++) {
            //     let only = this.data.selectedPeople.findIndex((item, index) => {
            //         return item.id == event[m]
            //     })
            // console.log(only.length);
            // if (only != -1 ) {
            //     wx.showToast({
            //         title: '重复勾选',
            //     })
            //     return
            // } else {
            //     for (var i = 0; i < len; i++) {
            //         let ind = user.findIndex((item, index) => {
            //             return item.id == event[i]
            //         })
            //         console.log(ind);
            //         this.data.selectedPeople.push(this.data.userInfo[ind])
            //         this.setData({
            //             selectedPeople: this.data.selectedPeople,
            //             show: false,
            //             result: []
            //         })
            //     }
            // }
            // }
        }
    },
    // 点击编辑跳到bookpeople页面
    edit(e) {
        let { id, name, phone, certificateno } = e.currentTarget.dataset
        wx.navigateTo({
            url: `../bookpeople/bookpeople?id=` + id + "&name=" + name + "&phone=" + phone + "&certificateno=" + certificateno,
        })
    },
    //从bookpeople页面返回 关闭下弹框
    onHide() {
        this.setData({
            show: false,
            result: []
        })
    },
    //点击新增
    newIncrease() {
        let who = 1
        this.setData({
            show: true,
            who
        })
    },
    //跳转到新客户页面
    toBookpeople(e) {
        let number = e.currentTarget.dataset.number
        wx.navigateTo({
            url: '../bookpeople/bookpeople?number=' + number
        })
    },
    //点击新增弹框里面的复选框
    newChange(e) {
        let newChecked = e.detail
        this.setData({
            newChecked
        })
    },
    //返回上一个界面
    reture() {
        console.log(1);
        wx.navigateBack({
            delta: 1,
        })
    },
    // 优惠券复选框
    onBottomChange(e) {
        let bottomcheck = e.detail
        this.setData({
            bottomcheck
        })
    },
    // 点击优惠券弹起优惠券列表
    chooseBgc() {
        let who = 2
        this.setData({
            show: true,
            who
        })
    },
    // 支付关闭
    onPayClose() {
        this.setData({
            payShow: false
        })
    },
    // 优惠券关闭
    onClose() {
        this.setData({
            show: false,
            result: [],
            couponArray: []
        })
    },
    //底部确定
    async determine() {
        if (this.data.selectedPeople.length == 0) {
            wx.showToast({
                title: '请添加一位购票人信息',
                icon: "none"
            })
            return
        }
        let userId = this.data.userDate.id
        let token = this.data.token
        let storeId = this.data.chooseTime.storeId
        let payment = this.data.totalPrice
        let venueId = this.data.chooseTime.venueId
        let venueName = this.data.chooseTime.venuName
    
        let { venueFieldId, venueTimeId, timePrice, appointmentDate } = this.data.chooseTime
        let buyerList = this.data.selectedPeople.map(item => {
            
            return { 
                name: item.name, 
                phone: item.phone, 
                certificateNo: item.certificateNo,
            }
        })
        console.log(buyerList);
        let option = {
            url: "/venueOrder/buyTicket",
            data: {
                userId,
                token,
                storeId,
                payment: Number(payment),
                venueId,
                venueName,
                venueFieldId: Number(venueFieldId),
                venueTimeId: Number(venueTimeId),
                timePrice: Number(timePrice),
                appointmentDate,
                buyerList,
                cityCouponNo:this.data.cityCouponNo
            },
            header: "content-type:application/json"
        }
        let res = await http(option)
        console.log(res);
        this.orderId = res.data.data //订单id
        if (res.data.status == 200) {
            this.orderNo = res.data.data
            this.toPaymeny(res.data.data)
        } else {
            common.showToast(res.data.msg)
        }
    },
    // 单选框
    onChange(e) {
        let checked = e.detail
        this.setData({
            checked,
            boxChecked: checked
        })
    }
})